package com.atstudent.gmall.common.service.impl;

import com.atstudent.gmall.common.properties.MinioProperties;
import com.atstudent.gmall.common.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.util.UUID;

/**
 * @ClassName：FileUploadServiceImpl
 * @Dexcription
 * @Author 薛有朋
 * @CreatDate 2024/11/23 12:46
 **/
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile multipartFile){

        try {
            //1.创建桶 不能每次创建一个 所以放在spring容易中管理 实行单例模式

            //2.查看是否存在桶,若不存在则创建
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucket()).build());
            if (!exists){//创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucket()).build());
            }

            //用uuid随机生成名称
            String uuidFileName = UUID.randomUUID().toString().replace("-", "");
            //拿到文件原名称 xxxx.jpg
            String originalFilename = multipartFile.getOriginalFilename();
            //拿到图片文件的后缀名 获取文件的扩展名(后缀 比如: .jpg)
            String extensionName = FilenameUtils.getExtension(originalFilename);
            //得到文件名称
            String fileName = uuidFileName + "." + extensionName;

            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName)
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);

            //访问文件路径
            String imageUrl = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + fileName;
            return imageUrl;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
